<?php

class pay extends CI_Model
{
    //金币进库
    function jb($je, $type, $state = 1, $content = '', $mid = 0, $did = 0)
    {
        //负数防御
        if ($type < 0) {
            $je_numb = $this->get_jb($mid);
            if ($je_numb < $je) {
                return 0;
            } else {
                $this->db->trans_start();
            }
        }


        $mid = $mid ? $mid : $this->session->userdata('mid');
        $didd = $type . '-' . $did . '-' . $mid;
        $q = $this->db->get_where('jb', array('didd' => $didd));
        if ($mid && $je > 0 && $q->num_rows() == 0) {
            $da['mid'] = $mid;
            $da['je'] = $je;
            $da['type'] = $type;
            $da['state'] = $state;
            $da['mktime'] = @mktime();
            $da['mkip'] = $this->input->ip_address();
            $da['content'] = $content;
            $da['did'] = $did;
            //唯一值
            $da['didd'] = $type . '-' . $did . '-' . $mid;
            $this->db->insert('jb', $da);
            $idx = $this->db->insert_id();
            if ($type < 0) {
                //判断数据是否需要回滚
                $je_numb = $this->get_jb($mid);
                if ($je_numb < 0 || $this->db->trans_status() === FALSE) {
                    $this->db->trans_rollback();
                    return 0;
                } else {
                    $this->db->trans_complete();
                }
            }
            return $idx;
        } else {
            return 0;
        }
    }

    //获取剩余金额
    function get_jb($mid = 0)
    {
        $mid = $mid ? $mid : $this->session->userdata('mid');
        if ($mid) {
            //获取消耗
            $this->db->where('mid', $mid);
            $this->db->where('type <', 0);
            $this->db->where('state >', 0);
            $this->db->select('sum(je)');
            $q = $this->db->get_where('jb');
            $xh = $q->row_array(0);
            //获取增值
            $this->db->where('mid', $mid);
            $this->db->where('type >', 0);
            $this->db->where('state >', 0);
            $this->db->select('sum(je)');
            $q = $this->db->get_where('jb');
            $zz = $q->row_array(0);

            $ls = $zz['sum(je)'] - $xh['sum(je)'];
            return sprintf("%.2f", $ls);;
        } else {
            return 0;
        }
    }


    //减少库存
    function jskc($sp_id, $numb = 0)
    {
        if ($this->input->post('color')) {
            $this->db->select('color');
            $q = $this->db->get_where('sp', array('sp_id' => $sp_id));
            $sp = $q->row_array(0);
            $color = implode('-', $this->input->post('color')) . '-kc';
            $colors = explode('&', $sp['color']);
            $set = array();
            foreach ($colors as $v) {
                $ls = explode('=', $v);
                if ($ls[0] == $color) {
                    $ls[1] = $ls[1] - $numb;
                }
                $set[] = $ls[0] . '=' . $ls[1];
            }
            $set_d = implode('&', $set);
            $this->db->query('update pan_sp set color=\'' . $set_d . '\' where sp_id=' . $sp_id);
        }

        return $this->db->query('update pan_sp set kc=kc-' . $numb . ' where sp_id=' . $sp_id);
    }

    //获取支付openid
    function get_pay_openid($mid, $bill_id)
    {
        $mid = $mid ? $mid : $this->session->userdata('mid');
        //当前使用的支付版本
        $pay_c = $this->config->item('pay_c');
        $pay = $this->config->item('pay');
        $da['mid'] = $mid;
        $da['type'] = 1;
        $da['edition'] = $pay_c;
        $this->db->where($da);
        $q = $this->db->get_where('openid');
        if ($q->num_rows() == 0) {
            $this->session->set_userdata('ls_url', '/wx_pay/ddzf/' . $bill_id);
            $ls = $this->config->item('base_urlx');
            $redirect_uri = $ls . '/wx_reg/up_openid_pay/';
            $wechat_redirect = 'lance';
            $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $pay[$pay_c]['wxAppId'] . '&redirect_uri=' . $redirect_uri . '&response_type=code&scope=snsapi_base&state=' . $wechat_redirect . '#wechat_redirect';
            redirect($url);
        } else {
            $ls = $q->row_array(0);
            return $ls['openid'];
        }
    }

    //获取发红包openid
    function get_hb_openid($mid, $ls_url = '/')
    {
        $mid = $mid ? $mid : $this->session->userdata('mid');
        //当前使用的支付版本
        $hb_c = $this->config->item('hb_c');
        $hb = $this->config->item('hb');
        $da['mid'] = $mid;
        $da['type'] = 2;
        $da['edition'] = $hb_c;
        $this->db->where($da);
        $q = $this->db->get_where('openid');
        if ($q->num_rows() == 0) {
            $this->session->set_userdata('ls_url', $ls_url);
            $ls = $this->config->item('base_urlx');
            $redirect_uri = $ls . '/wx_reg/up_openid_hb/';
            $wechat_redirect = 'lance';
            $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $hb[$hb_c]['wxAppId'] . '&redirect_uri=' . $redirect_uri . '&response_type=code&scope=snsapi_base&state=' . $wechat_redirect . '#wechat_redirect';
            redirect($url);
        } else {
            $ls = $q->row_array(0);
            return $ls['openid'];
        }
    }

    //发红包  total_amount 总金额  $act_name 活动名称   $send_name 发送者名称   $wishing 祝福语
    function send_hb($jb_id, $ls_url)
    {
        $q = $this->db->get_where('jb', array('id' => $jb_id, 'type' => -5));
        if ($q->num_rows() > 0) {
            $jb_bill = $q->row_array(0);

            //获取openid
            $openid = $this->get_hb_openid($jb_bill['mid'], $ls_url);

            $total_amount = $jb_bill['je'] * 100;
            $this->load->helper('string');

            $arcr['mch_appid'] = $this->config->item('wxAppId');
            $arcr['mchid'] = $this->config->item('partnerid');

            $arcr['nonce_str'] = random_string('alnum', 16);

            $arcr['partner_trade_no'] = $arcr['mchid'] . $jb_id;

            $arcr['openid'] = $openid;

            $arcr['check_name'] = 'NO_CHECK';

            $arcr['amount'] = $total_amount;
            $arcr['desc'] = $jb_bill['content'];

            $arcr['spbill_create_ip'] = $this->input->ip_address();

            ksort($arcr);

            $ls = array();
            foreach ($arcr as $k => $v) {
                $ls[] = $k . '=' . $v;
            }
            $arcr['sign'] = strtoupper(md5(implode('&', $ls) . '&key=' . $this->config->item('partnerkey')));

            $resultStr = '<xml>';
            foreach ($arcr as $k => $v) {
                $resultStr .= ' <' . $k . '><![CDATA[' . $v . ']]></' . $k . '>';
            }
            $resultStr .= '</xml>';

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers");
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $resultStr);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSLCERT, $this->config->item('cacert_pay') . 'apiclient_cert.pem');
            curl_setopt($ch, CURLOPT_SSLKEY, $this->config->item('cacert_pay') . 'apiclient_key.pem');
            curl_setopt($ch, CURLOPT_CAINFO, $this->config->item('cacert_pay') . 'rootca.pem');
            $tmpInfo = curl_exec($ch);
            $tmpInfo = str_replace('<![CDATA[', '', $tmpInfo);
            $tmpInfo = str_replace(']]>', '', $tmpInfo);

            if (curl_errno($ch)) {
                $re['state'] = FALSE;
                $re['error'] = curl_error($ch);
            }
            curl_close($ch);
            $arr = json_decode(json_encode((array)simplexml_load_string($tmpInfo)), true);
            $re['bk'] = $arr;
            if ($arr['result_code'] == 'SUCCESS') {
                $re['state'] = TRUE;
                $re['error'] = '';
            } else {
                $re['state'] = FALSE;
                $re['error'] = $arr['return_msg'];
            }

            $in_log['send'] = json_encode($arcr);
            $in_log['back'] = json_encode($arr);
            $in_log['jb_id'] = $jb_id;
            $in_log['mid'] = $jb_bill['mid'];
            $in_log['mktime'] = mktime();
            $this->db->insert('jb_log', $in_log);
        } else {
            $re['state'] = FALSE;
            $re['error'] = '订单不存在';
        }


        return $re;
    }

    //企业付款
    function send_fk($jb_id, $ls_url)
    {
        $q = $this->db->get_where('jb', array('id' => $jb_id, 'type' => -1));
        if ($q->num_rows() > 0) {
            $jb_bill = $q->row_array(0);
            //获取openid
            $openid = $this->get_hb_openid($jb_bill['mid'], $ls_url);

            $total_amount = $jb_bill['je'] * 100;
            $this->load->helper('string');

            $arcr['mch_appid'] = $this->config->item('wxAppId_zfd');
            $arcr['mchid'] = $this->config->item('partnerid_zfd');

            $arcr['nonce_str'] = random_string('alnum', 16);

            $arcr['partner_trade_no'] = $arcr['mchid'] . $jb_id;

            $arcr['openid'] = $openid;

            $arcr['check_name'] = 'NO_CHECK';

            $arcr['amount'] = $total_amount;
            $arcr['desc'] = $jb_bill['content'];

            $arcr['spbill_create_ip'] = $this->input->ip_address();

            ksort($arcr);

            $ls = array();
            foreach ($arcr as $k => $v) {
                $ls[] = $k . '=' . $v;
            }
            $arcr['sign'] = strtoupper(md5(implode('&', $ls) . '&key=' . $this->config->item('partnerkey_zfd')));

            $resultStr = '<xml>';
            foreach ($arcr as $k => $v) {
                $resultStr .= ' <' . $k . '><![CDATA[' . $v . ']]></' . $k . '>';
            }
            $resultStr .= '</xml>';

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers");
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $resultStr);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSLCERT, $this->config->item('cacert_pay_zfd') . 'apiclient_cert.pem');
            curl_setopt($ch, CURLOPT_SSLKEY, $this->config->item('cacert_pay_zfd') . 'apiclient_key.pem');
            curl_setopt($ch, CURLOPT_CAINFO, $this->config->item('cacert_pay_zfd') . 'rootca.pem');
            $tmpInfo = curl_exec($ch);
            $tmpInfo = str_replace('<![CDATA[', '', $tmpInfo);
            $tmpInfo = str_replace(']]>', '', $tmpInfo);

            if (curl_errno($ch)) {
                $re['state'] = FALSE;
                $re['error'] = curl_error($ch);
            }
            curl_close($ch);
            $arr = json_decode(json_encode((array)simplexml_load_string($tmpInfo)), true);
            $re['bk'] = $arr;
            if ($arr['result_code'] == 'SUCCESS') {
                $re['state'] = TRUE;
                $re['error'] = '';
            } else {
                $re['state'] = FALSE;
                $re['error'] = $arr['return_msg'];
            }

            $in_log['send'] = json_encode($arcr);
            $in_log['back'] = json_encode($arr);
            $in_log['jb_id'] = $jb_id;
            $in_log['mid'] = $jb_bill['mid'];
            $in_log['mktime'] = mktime();
            $this->db->insert('jb_log', $in_log);
        } else {
            $re['state'] = FALSE;
            $re['error'] = '订单不存在';
        }

        return $re;
    }


}

?>